package com.molichuxing.gateway.api.services.impl;

import com.molichuxing.framework.exception.BizException;
import com.molichuxing.framework.result.ResponseResult;
import com.molichuxing.gateway.api.services.FinancialApiService;
import com.molichuxing.gateway.bff.financial.entity.request.create.InvoiceCreateVo;
import com.molichuxing.gateway.bff.financial.entity.response.ContractVo;
import com.molichuxing.gateway.bff.financial.entity.response.ConvertSendEmailVo;
import com.molichuxing.gateway.bff.financial.entity.response.InvoiceVo;
import com.molichuxing.gateway.bff.financial.services.ContractBffService;
import com.molichuxing.gateway.bff.financial.services.InvoiceBffService;
import com.molichuxing.gateway.bff.user.entity.response.UserVo;
import com.molichuxing.gateway.utils.RequestAttrUtil;
import com.molichuxing.services.property.InvoiceTitleTypeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 财务相关接口
 *
 * @author zhaopenghui
 * @date 2019年9月25日
 */
@Api(tags = "财务相关接口")
@RestController
@RequestMapping(value = "/financial")
public class FinancialApiServiceImpl extends RootApiService implements FinancialApiService {
	private static final Logger logger = LoggerFactory.getLogger(FinancialApiServiceImpl.class);

	@Resource
	InvoiceBffService invoiceBffService;

	@Resource
	ContractBffService contractBffService;

	@Override
	@ApiOperation(value = "开票列表")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "status", value = "状态(1：未申请，2：已申请，3：已过期)", required = false, dataType = "Integer"), })
	@GetMapping(value = "/invoice/list")
	public ResponseResult<List<InvoiceVo>> getInvoicePage(@RequestParam Map<String, Object> map) {
		ResponseResult<List<InvoiceVo>> result = new ResponseResult<>();
		try {
			UserVo currentUser = RequestAttrUtil.getCurrentUser();
			if (currentUser != null) {
				Integer userId = currentUser.getUserId();
				map.put("userId", userId);
			}

			return result.success(invoiceBffService.getInvoicePage(map));
		} catch (BizException e) {
			logger.error("[getInvoicePage]获取开票列表异常", e);
			result.error(e.getExceptionCode(), e.getMessage());
		} catch (Exception e) {
			logger.error("[getInvoicePage]获取开票列表异常", e);
			result.error("获取开票列表异常");
		}
		return result;
	}

	/**
	 * 发票添加
	 *
	 * @param invoiceCreateVo
	 * @return
	 */
	@Override
	@ApiOperation(value = "申请开票")
	@PostMapping(value = "/invoice/create")
	public ResponseResult<Boolean> createInvoice(@RequestBody @Valid InvoiceCreateVo invoiceCreateVo) {
		ResponseResult<Boolean> result = new ResponseResult<>();
		try {
			String purchaserTaxNumber = invoiceCreateVo.getPurchaserTaxNumber();
			Integer invoiceTitleType = invoiceCreateVo.getInvoiceTitleType();
			if (InvoiceTitleTypeEnum.ENTERPRISE.getValue() == invoiceTitleType) {
				if (purchaserTaxNumber.length() != 15 && purchaserTaxNumber.length() != 18
						&& purchaserTaxNumber.length() != 20) {
					logger.error("税号长度不正确" + purchaserTaxNumber);
					throw new BizException("税号格式错误！请重新输入");
				}
			}

			UserVo currentUser = RequestAttrUtil.getCurrentUser();
			Integer userId = null;
			if (currentUser != null) {
				userId = currentUser.getUserId();
			}
			return result.success(invoiceBffService.createInvoiceApply(invoiceCreateVo, userId));
		} catch (BizException e) {
			logger.error("[createInvoice]申请开票异常", e);
			result.error(e.getExceptionCode(), e.getMessage());
		} catch (Exception e) {
			logger.error("[createInvoice]申请开票异常", e);
			result.error("申请开票异常");
		}
		return result;
	}

	/**
	 * 合同列表
	 *
	 * @param orderCode
	 * @return
	 */
	@Override
	@ApiOperation(value = "合同列表")
	@ApiImplicitParams({ @ApiImplicitParam(name = "orderCode", value = "订单编号", required = true, dataType = "Long"), })
	@GetMapping(value = "/contract/list")
	public ResponseResult<List<ContractVo>> getContractList(@RequestParam Long orderCode) {
		ResponseResult<List<ContractVo>> result = new ResponseResult<>();
		try {
			if (null == orderCode) {
				result.error("请选择订单");
			}

			return result.success(contractBffService.getContractList(orderCode));
		} catch (BizException e) {
			logger.error("[getContractList]获取合同列表异常", e);
			result.error(e.getExceptionCode(), e.getMessage());
		} catch (Exception e) {
			logger.error("[getContractList]获取合同列表异常", e);
			result.error("获取合同列表异常");
		}
		return result;
	}

	/**
	 * 发送邮件
	 *
	 * @param convertSendEmailVo
	 * @return
	 */
	@Override
	@ApiOperation(value = "发送邮箱")
	@PostMapping(value = "/contract/send/email")
	public ResponseResult<Boolean> sendEmailAttachments(@RequestBody @Valid ConvertSendEmailVo convertSendEmailVo) {
		ResponseResult<Boolean> result = new ResponseResult<>();
		try {
			return result.success(contractBffService.sendEmailAttachments(convertSendEmailVo));
		} catch (BizException e) {
			logger.error("[sendEmailAttachments]发送邮箱异常", e);
			result.error(e.getExceptionCode(), e.getMessage());
		} catch (Exception e) {
			logger.error("[sendEmailAttachments]发送邮箱异常", e);
			result.error("发送邮箱异常");
		}
		return result;
	}

	@ApiIgnore
	@GetMapping(value = "/contract/create")
	public ResponseResult<Boolean> createContractByRenege(@RequestHeader(value = "temporary", required = true) String temporary,
	                                                      @RequestParam Long orderCode, @RequestParam Integer userId) {
		ResponseResult<Boolean> result = new ResponseResult<>();
		try {
			if (temporary == null || !temporary.equals("temporary")) {
				return result.error("无效操作");
			}
			return result.success(contractBffService.createContractByRenege(orderCode, userId));
		} catch (BizException e) {
			logger.error("[createContractByRenege]生成退租协议异常", e);
			result.error(e.getExceptionCode(), e.getMessage());
		} catch (Exception e) {
			logger.error("[createContractByRenege]生成退租协议异常", e);
			result.error("生成退租协议异常");
		}
		return result;
	}


}
